<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="queryParams.processDefinitionId"
        :placeholder="'流程定义ID'"
        class="filter-item search-item"
      />

      <el-select
        v-model="queryParams.status"
        placeholder="请选择流程实例状态"
        class="filter-item search-item"
      >
        <el-option label="已结束" value="0"></el-option>
        <el-option label="正在运行" value="1"></el-option>
      </el-select>

      <el-button class="filter-item" type="primary" plain @click="search">
        查询
      </el-button>
      <el-button class="filter-item" type="warning" plain @click="reset">
        重置
      </el-button>
    </div>
    <el-table
      ref="table"
      :key="tableKey"
      v-loading="loading"
      :data="list"
      border
      fit
      style="width: 100%"
    >
      <el-table-column
        :label="'流程实例标识'"
        prop="id"
        :show-overflow-tooltip="true"
        align="center"
        min-width="100px"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.processInstanceId }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="'流程定义标识'"
        prop="id"
        :show-overflow-tooltip="true"
        align="center"
        min-width="100px"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.processDefinitionId }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="'流程定义KEY'"
        prop="id"
        :show-overflow-tooltip="true"
        align="center"
        min-width="100px"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.processDefinitionKey }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="'名称'" class-name="status-col">
        <template slot-scope="scope">
          <span>{{ scope.row.processDefinitionName }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="'版本'" class-name="status-col">
        <template slot-scope="scope">
          <span>{{ scope.row.processDefinitionVersion }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="'开始时间'" class-name="status-col">
        <template slot-scope="scope">
          <span>{{ scope.row.startTime }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="'发起用户'" class-name="status-col">
        <template slot-scope="scope">
          <span>{{ scope.row.startUserId }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="'结束时间'" class-name="status-col">
        <template slot-scope="scope">
          <span>{{ scope.row.endTime }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="'流程实例状态'" class-name="status-col">
        <template slot-scope="scope">
          <span>{{ scope.row.endTime }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="'操作'"
        align="center"
        min-width="100px"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row }">
          <i
            class="el-icon-edit table-operation"
            style="color: #2db7f5"
            @click="readSource(row)"
            >流程轨迹</i
          >
          <i
            v-if="!row.isFinished && row.suspended"
            class="el-icon-edit table-operation"
            style="color: #2db7f5"
            @click="activiti(row)"
            >激活</i
          >
          <i
            v-if="!row.isFinished && !row.suspended"
            class="el-icon-edit table-operation"
            style="color: #2db7f5"
            @click="suspended(row)"
            >挂起</i
          >
          <i
            class="el-icon-edit table-operation"
            style="color: #2db7f5"
            @click="getHistoryActInstanceList(row)"
            >历史活动</i
          >
          <i
            class="el-icon-edit table-operation"
            style="color: #2db7f5"
            @click="getHistoryProcessVariables(row)"
            >流程变量</i
          >
          <i
            class="el-icon-edit table-operation"
            style="color: #2db7f5"
            @click="getHistoryTaskList(row)"
            >历史任务</i
          >
          <i
            v-if="!row.isFinished"
            class="el-icon-delete table-operation"
            style="color: #f50"
            @click="deleteProcessInstance(row)"
            >撤销任务</i
          >
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
      :title="'流程活动'"
      width="40%"
      top="50px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="showImg"
    >
      <el-image :src="captchaImg"> </el-image>
    </el-dialog>
    <el-dialog
      :title="title"
      width="80%"
      top="50px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="showActiviti"
    >
      <div class="app-container">
        <div class="filter-container">
          <el-table
            ref="table"
            :key="tableKey"
            v-loading="loading"
            :data="activitiList"
            border
            fit
            style="width: 100%"
          >
            <el-table-column
              :label="'流程活动标识'"
              prop="id"
              :show-overflow-tooltip="true"
              align="center"
              min-width="100px"
            >
              <template slot-scope="scope">
                <span>{{ scope.row.activityId }}</span>
              </template>
            </el-table-column>
            <el-table-column
              :label="'流程活动名称'"
              prop="id"
              :show-overflow-tooltip="true"
              align="center"
              min-width="100px"
            >
              <template slot-scope="scope">
                <span>{{ scope.row.activityName }}</span>
              </template>
            </el-table-column>
            <el-table-column
              :label="'流程活动类型'"
              prop="id"
              :show-overflow-tooltip="true"
              align="center"
              min-width="100px"
            >
              <template slot-scope="scope">
                <span>{{ scope.row.activityType }}</span>
              </template>
            </el-table-column>
            <el-table-column :label="'发起时间'" class-name="status-col">
              <template slot-scope="scope">
                <span>{{ scope.row.startTime }}</span>
              </template>
            </el-table-column>
            <el-table-column :label="'流程定义标识'" class-name="status-col">
              <template slot-scope="scope">
                <span>{{ scope.row.processDefinitionId }}</span>
              </template>
            </el-table-column>
            <el-table-column :label="'流程实例标识'" class-name="status-col">
              <template slot-scope="scope">
                <span>{{ scope.row.processInstanceId }}</span>
              </template>
            </el-table-column>
            <el-table-column :label="'结束时间'" class-name="status-col">
              <template slot-scope="scope">
                <span>{{ scope.row.endTime }}</span>
              </template>
            </el-table-column>
            <el-table-column :label="'审批人'" class-name="status-col">
              <template slot-scope="scope">
                <span>{{ scope.row.assignee }}</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-dialog>

    <el-dialog
      :title="'历史任务'"
      width="80%"
      top="50px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="showTask"
    >
      <div class="app-container">
        <div class="filter-container">
          <el-table
            ref="table"
            :key="tableKey"
            v-loading="loading"
            :data="taskList"
            border
            fit
            style="width: 100%"
          >
            <el-table-column
              :label="'任务标识'"
              prop="id"
              :show-overflow-tooltip="true"
              align="center"
              min-width="100px"
            >
              <template slot-scope="scope">
                <span>{{ scope.row.id }}</span>
              </template>
            </el-table-column>
            <el-table-column
              :label="'任务名称'"
              prop="id"
              :show-overflow-tooltip="true"
              align="center"
              min-width="100px"
            >
              <template slot-scope="scope">
                <span>{{ scope.row.name }}</span>
              </template>
            </el-table-column>
            <el-table-column
              :label="'任务创建时间'"
              prop="id"
              :show-overflow-tooltip="true"
              align="center"
              min-width="100px"
            >
              <template slot-scope="scope">
                <span>{{ scope.row.createTime }}</span>
              </template>
            </el-table-column>
            <el-table-column
              :label="'任务签收时间'"
              prop="id"
              :show-overflow-tooltip="true"
              align="center"
              min-width="100px"
            >
              <template slot-scope="scope">
                <span>{{ scope.row.claimTime }}</span>
              </template>
            </el-table-column>
            <el-table-column :label="'签收人'" class-name="status-col">
              <template slot-scope="scope">
                <span>{{ scope.row.assignee }}</span>
              </template>
            </el-table-column>
            <el-table-column :label="'任务定义KEY'" class-name="status-col">
              <template slot-scope="scope">
                <span>{{ scope.row.taskDefinitionKey }}</span>
              </template>
            </el-table-column>
            <el-table-column :label="'流程定义标识'" class-name="status-col">
              <template slot-scope="scope">
                <span>{{ scope.row.processDefinitionId }}</span>
              </template>
            </el-table-column>
            <el-table-column :label="'流程实例标识'" class-name="status-col">
              <template slot-scope="scope">
                <span>{{ scope.row.processInstanceId }}</span>
              </template>
            </el-table-column>
            <el-table-column :label="'任务结束时间'" class-name="status-col">
              <template slot-scope="scope">
                <span>{{ scope.row.endTime }}</span>
              </template>
            </el-table-column>
            <el-table-column :label="'任务撤销原因'" class-name="status-col">
              <template slot-scope="scope">
                <span>{{ scope.row.deleteReason }}</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-dialog>

    <el-dialog
      :title="'流程变量'"
      width="80%"
      top="50px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="showVariable"
    >
      <div class="app-container">
        <div class="filter-container">
          <el-table
            ref="table"
            :key="tableKey"
            v-loading="loading"
            :data="variableList"
            border
            fit
            style="width: 100%"
          >
            <el-table-column
              :label="'参数标识'"
              prop="id"
              :show-overflow-tooltip="true"
              align="center"
              min-width="100px"
            >
              <template slot-scope="scope">
                <span>{{ scope.row.id }}</span>
              </template>
            </el-table-column>
            <el-table-column
              :label="'参数名称'"
              prop="id"
              :show-overflow-tooltip="true"
              align="center"
              min-width="100px"
            >
              <template slot-scope="scope">
                <span>{{ scope.row.variableName }}</span>
              </template>
            </el-table-column>
            <el-table-column
              :label="'参数类型'"
              prop="id"
              :show-overflow-tooltip="true"
              align="center"
              min-width="100px"
            >
              <template slot-scope="scope">
                <span>{{ scope.row.variableTypeName }}</span>
              </template>
            </el-table-column>
            <el-table-column
              :label="'参数值'"
              prop="id"
              :show-overflow-tooltip="true"
              align="center"
              min-width="100px"
            >
              <template slot-scope="scope">
                <span>{{ scope.row.value }}</span>
              </template>
            </el-table-column>
            <el-table-column :label="'创建时间'" class-name="status-col">
              <template slot-scope="scope">
                <span>{{ scope.row.createTime }}</span>
              </template>
            </el-table-column>
            <el-table-column :label="'最后更新时间'" class-name="status-col">
              <template slot-scope="scope">
                <span>{{ scope.row.lastUpdatedTime }}</span>
              </template>
            </el-table-column>
            <el-table-column :label="'流程实例标识'" class-name="status-col">
              <template slot-scope="scope">
                <span>{{ scope.row.processInstanceId }}</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-dialog>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="pagination.num"
      :limit.sync="pagination.size"
      @pagination="fetch"
    />
  </div>
</template>

<script>
import axios from "axios";
import { getToken } from "@/utils/auth";
import Pagination from "@/components/Pagination";
export default {
  name: "processdefinition",
  components: { Pagination },
  filters: {
    state(value) {
      if (value == "1") {
        return "已激活";
      } else if (value == "2") {
        return "已挂起";
      }
    }
  },
  data() {
    return {
      title: "",
      showTask: false,
      showActiviti: false,
      showVariable: false,
      headers: {
        Authorization: `bearer ${getToken()}`
      },
      title: "流程轨迹",
      showImg: false,
      captchaImg: "",
      activitiList: [],
      taskList: [],
      variableList: [],
      isVisible: false,
      dialog: {
        isVisible: false,
        title: ""
      },
      workflowVisible: false,
      tableKey: 0,
      loading: false,
      list: null,
      total: 0,
      queryParams: { processDefinitionId: "", status: "0" },
      sort: {},
      selection: [],
      pagination: {
        size: 10,
        num: 1
      }
    };
  },
  computed: {
    currentUser() {
      return this.$store.state.account.user;
    }
  },
  // 生成页面
  mounted() {
    // this.fetch();
  },
  methods: {
    deleteProcessInstance(row) {
      var queryObj = {
        processInstanceId: row.id
      };
      this.$delete(`/activiti/service/process/deleteProcessInstance`, {
        ...queryObj
      }).then(res => {
        this.$message.success("撤销成功");
        this.search();
      });
    },
    activiti(row) {
      var queryObj = {
        processInstanceId: row.id,
        suspendState: "1"
      };
      this.$post(`/activiti/service/process/suspendProcessInstance`, {
        ...queryObj
      }).then(res => {
        this.$message.success("激活成功");
        this.search();
      });
    },
    suspended(row) {
      var queryObj = {
        processInstanceId: row.id,
        suspendState: "2"
      };
      this.$post(`/activiti/service/process/suspendProcessInstance`, {
        ...queryObj
      }).then(res => {
        this.$message.success("挂起成功");
        this.search();
      });
    },
    readSource(row) {
      axios({
        method: "GET",
        url: `/activiti/service/process/readResource/${row.id}`,
        responseType: "arraybuffer",
        headers: {
          Authorization: `bearer ${getToken()}`
        }
      })
        .then(res => {
          return (
            "data:image/png;base64," +
            btoa(
              new Uint8Array(res.data).reduce(
                (data, byte) => data + String.fromCharCode(byte),
                ""
              )
            )
          );
        })
        .then(res => {
          this.captchaImg = res;
          this.showImg = true;
        })
        .catch(e => {
          if (e.toString().indexOf("429") !== -1) {
            this.$message({
              message: this.$t("tips.tooManyRequest"),
              type: "error"
            });
          } else {
            this.$message({
              message: this.$t("获取流程轨迹图失败！"),
              type: "error"
            });
          }
        });
    },
    getHistoryProcessVariables(row) {
      var queryObj = {
        processInstanceId: row.id
      };
      this.$get(`/activiti/service/processHistory/getHistoryProcessVariables`, {
        ...queryObj
      }).then(res => {
        this.showVariable = true;
        this.variableList = res.data.resultBody;
      });
    },
    getHistoryTaskList(row) {
      var queryObj = {
        processInstanceId: row.id
      };
      this.$get(`/activiti/service/processHistory/getHistoryTaskList`, {
        ...queryObj
      }).then(res => {
        this.showTask = true;
        this.taskList = res.data.resultBody;
      });
    },
    getHistoryActInstanceList(row) {
      var queryObj = {
        processInstanceId: row.id
      };
      this.$get(`/activiti/service/processHistory/getHistoryActInstanceList`, {
        ...queryObj
      }).then(res => {
        this.showActiviti = true;
        this.activitiList = res.data.resultBody;
      });
    },
    search() {
      if (
        this.queryParams.processDefinitionId == "" ||
        this.queryParams.processDefinitionId == null
      ) {
        this.$message.warning("请输入流程定义ID！");
        return;
      }
      this.fetch({
        ...this.queryParams,
        ...this.sort
      });
    },
    reset() {
      this.queryParams = {};
      this.sort = {};
      this.$refs.table.clearSort();
      this.$refs.table.clearFilter();
      // this.search();
    },
    singleDelete(row) {
      this.$refs.table.toggleRowSelection(row, true);
      this.batchDelete();
    },
    batchDelete() {
      if (!this.selection.length) {
        this.$message({
          message: this.$t("tips.noDataSelected"),
          type: "warning"
        });
        return;
      }
      const contain = false;
      this.$confirm(this.$t("tips.confirmDelete"), this.$t("common.tips"), {
        confirmButtonText: this.$t("common.confirm"),
        cancelButtonText: this.$t("common.cancel"),
        type: "warning"
      })
        .then(() => {
          const flowIds = [];
          this.selection.forEach(u => {
            flowIds.push(u.deployment.id);
          });
          this.delete(flowIds);
        })
        .catch(() => {
          this.clearSelections();
        });
    },
    delete(deploymentId) {
      this.loading = true;
      this.$get(
        `/activiti/service/definition/process/delete/${deploymentId}`
      ).then(() => {
        this.$message({
          message: this.$t("tips.deleteSuccess"),
          type: "success"
        });
        this.search();
      });
    },
    fetch(params = {}) {
      if (
        this.queryParams.processDefinitionId == "" ||
        this.queryParams.processDefinitionId == null
      ) {
        this.$message.warning("请输入流程定义ID！");
        return;
      }
      var _this = this;
      params.pageSize = _this.pagination.size;
      params.pageNum = _this.pagination.num;
      _this.loading = true;
      if (this.queryParams.status == "0") {
        _this
          .$get("activiti/service/processHistory/getFinishedInstanceList", {
            ...params
          })
          .then(r => {
            const data = r.data.resultBody;
            _this.total = data.total;
            _this.list = data.records;
            _this.loading = false;
          });
      } else if (this.queryParams.status == "1") {
        _this
          .$get("activiti/service/processHistory/queryRuntimeInstance", {
            ...params
          })
          .then(r => {
            const data = r.data.resultBody;
            _this.total = data.total;
            _this.list = data.records;
            _this.loading = false;
          });
      }
    }
  }
};
</script>
<style lang="scss" scoped></style>
